<?php
namespace zhtfrontend\controllers;

use common\models\datas\Student;
use Yii;
use common\models\datas\Balance;
use common\models\datas\BalanceRelation;
use common\models\datas\Classhourfee;
use doumiaoduo\buildform\BuildForm;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\CheckCount;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Mechanic;
use yii\data\Pagination;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use zhtfrontend\models\datas\MechanicSettlement;
use zhtfrontend\models\datas\MechanicSettlementRelation;
use zhtfrontend\models\datas\MechanicSettlementSubsidy;
use zhtfrontend\models\datas\MechanicSettlementVoucher;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\ReportRecord;
use yii\widgets\ActiveForm;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\SubstituteCheck;

class ClasshouraccountController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $get = \Yii::$app->request->get();
        $model = MechanicSettlement::find();
        if(!empty($get['mechanic_name'])){
            $mechanic = Mechanic::find()->where(['like','name',trim($get['mechanic_name'])])->one();
            if($mechanic != null) $mechanic_id = $mechanic->id;else $mechanic_id = null;
            $model->andWhere(['mechanic_id'=>$mechanic_id]);
        }
        if(\Yii::$app->user->identity->role == 'class_director'){
            $module_ids = ReportRecord::find()->select('module_id')->where(['type'=>2,'sendee_id'=>\Yii::$app->user->id])->groupBy('module_id')->column();
            $model->andWhere(['id'=>$module_ids]);
        }
        if(!empty($get['id'])){
            $model->andWhere(['id'=>$get['id']]);
        }
        $model->orderBy('id DESC');
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => 14, 'params' => $_GET]);
        isset($get['page']) ? $pages->page = $get['page'] - 1 : 0;
        $data = $model->offset($pages->offset)->limit($pages->limit)->all();
        $data = Fun::asArray($data,['pay_status_name','mechanic_name','process','operate']);
        return $this->render('index',['data'=>$data,'months'=>[],'pages'=>$pages]);
    }

    /**
     *  教服设置额外加嗯
     */
    public function actionSet(){
        $this->layout='@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $model = MechanicSettlement::findOne($id);
        $subsidyList = MechanicSettlementSubsidy::find()->where(['mechanic_settlement_id'=>$id])->all();
        if(\Yii::$app->request->isPost && \Yii::$app->request->post()){
           // $allids = MechanicSettlementSubsidy::find()->select('id')->where(['mechanic_settlement_id'=>$id])->column();
            $post = \Yii::$app->request->post();
            $moneys = $post['money'];
            $remarks = $post['remark'];
            $ids = $post['ids'];
            MechanicSettlementSubsidy::deleteAll(['AND', 'mechanic_settlement_id = :mechanic_settlement_id', ['NOT IN', 'id', $ids]], [':mechanic_settlement_id' => $id]);
            if(!empty($moneys)){
                foreach ($moneys as $k=>$val){
                    if(!empty((float)$val) && !empty($remarks[$k])){
                        if($ids[$k] > 0){
                            $modeloldSubsidy = MechanicSettlementSubsidy::findOne($ids[$k]);
                            $modeloldSubsidy->money = (float)$val;
                            $modeloldSubsidy->remark = $remarks[$k];
                            $modeloldSubsidy->save(false);
                        }else {
                            $modelSubsidy = new MechanicSettlementSubsidy();
                            $modelSubsidy->mechanic_settlement_id = $id;
                            $modelSubsidy->money = (float)$val;
                            $modelSubsidy->remark = $remarks[$k];
                            $modelSubsidy->save(false);
                        }
                    }
                }
            }
            $sum = MechanicSettlementSubsidy::find()->where(['mechanic_settlement_id'=>$id])->sum('money');
            if($sum != null){
                $model->additional_money = $sum;
                $model->total = $model->commission_money+$model->subsidy_money+$sum;
                $model->save(false);
            }
            return $this->redirectMessage(\Yii::t('zhtfrontend', '设置成功'), Fun::url(['classhouraccount/index']));

        }
        return $this->render('set',['data'=>$subsidyList]);
    }

    /**
     *  核实数据
     */
    public function actionVerify(){
        $this->layout='@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $modelMechanic = MechanicSettlement::findOne($id);
        $model = new ReportRecord();
        $model->is_visual = 1;
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post())&& $model->validate()) {
                $model->module_id = $id;
                $model->sender_id = \Yii::$app->user->id;
                if(\Yii::$app->user->identity->role == 'class_director'){
                    $stage = 11;
                    if($model->status == 1){
                        $row = Admin::find()->where(['mechanic_id'=>$modelMechanic->mechanic_id,'role'=>'mec_principal','status'=>1])->one();
                        $sendee_id = $row->id;
                    }else{
                        $row = ReportRecord::find()->where(['type'=>2,'stage'=>10,'module_id'=>$id])->orderBy('id DESC')->one();
                        $sendee_id = $row->sender_id;
                    }
                }else{
                    $stage = 13;
                    if($model->status == 1){
                        $mechanic = Mechanic::findOne($modelMechanic->mechanic_id);
                        $sendee_id = $mechanic->admin_id;
                    }else{
                        $row = ReportRecord::find()->where(['type'=>2,'stage'=>10,'module_id'=>$id])->orderBy('id DESC')->one();
                        $sendee_id = $row->sender_id;
                    }
                }

                $model->sendee_id = $sendee_id;
                $model->stage = $stage;
                $model->type = 2;
                $model->workerremark = $model->remark;
                $model->operator_type = 'square';
                $model->save(false);

            $modelMechanic->status = $stage;
            $modelMechanic->save(false);
            return $this->redirectMessage(\Yii::t('zhtfrontend', '设置成功'), Fun::url(['classhouraccount/index']));
        }

        return $this->render('verify',['model'=>$model]);
    }

    /**
     * Displays a single Settlement model.
     */
    public function actionView()
    {
        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $id = \Yii::$app->request->get('id');
        $model = MechanicSettlement::findOne($id);

        $reportList = ReportRecord::find()->where(['module_id'=>$id,'type'=>2])->orderBy('id DESC')->all();
        $data = Fun::asArray($reportList,['sender_name','sendee_name','remark']);
        $Subsidy = MechanicSettlementSubsidy::find()->where(['mechanic_settlement_id'=>$id])->all();


        $stage = [10=>'教务生成结算报表',11=>'教服审核',12=>'机构负责人审核',13=>'财务审核',14=>'财务已付款'];

        return $this->render('view', ['model'=>$model,'reportList'=>$data,'subsidy'=>$Subsidy,'stage'=>$stage]);
    }

    //结算
    public function actionState(){
        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $id = \Yii::$app->request->get('id');
        $modelmechanic = MechanicSettlement::findOne($id);
        if ($modelmechanic == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = new MechanicSettlementVoucher();
        $model->status = 1;
        $form = new BuildForm('@app/components/forms/balanceForm.php');
        $form->loadModel(['balance' => $model]);
        $form->loadDefaultValues();
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model->mechanic_settlement_id = $id;
            $model->operator = Yii::$app->user->identity->name;
            $model->operator_id = Yii::$app->user->id;
            if ($model->save(false)) {
                $modelmechanic->pay_status = $model->status;
                $modelmechanic->paymant_operator = Yii::$app->user->identity->name;
                $modelmechanic->paymant_operator_id = Yii::$app->user->id;
                $modelmechanic->payment_time = time();
                $modelmechanic->save(false);
                $mechanic = Mechanic::findOne($modelmechanic->mechanic_id);
                $sendee_id = $mechanic->admin_id;
                $models = new ReportRecord();
                $models->module_id = $id;
                $models->sender_id = \Yii::$app->user->id;
                $models->sendee_id = $sendee_id;
                $models->stage = 14;
                $models->type = 2;
                $models->workerremark = '';
                $models->operator_type = 'square';
                $models->status = 1;
                $models->save(false);
                return $this->redirectMessage(\Yii::t('zhtfrontend', '结算成功'), Fun::url(['classhouraccount/index']));
            }
        }
        return $this->render('settlement', ['form' => $form->render(),'modelmechanic'=>$modelmechanic]);
    }

    public function actionClassfire(){
        $this->layout='@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id  == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $ids = MechanicSettlementRelation::find()->select('checkcount_id')->where(['mechanic_settlement_id'=>$id])->column();
        $checkList = CheckCount::find()->where(['id'=>$ids])->all();
        $data = Fun::asArray($checkList,['teacher_name','student','course','class_type']);
        return $this->render('classfire', ['data' => $data]);
    }

    public function actionImportfrie($page=0){
         $model = StudentCheck::find()->where(['status'=>1]);
        isset($page) ? $page - 1 : 0;
        $data = $model->offset($page)->limit(10)->all();
        $datas = [];
        foreach ($data as $item){
           $classstudent = ClassStudent::findOne($item->class_student_id);
           $LessonModel = ClassLesson::findOne($item->class_lesson_id);
           $class_id = isset($LessonModel->classManage->class_id)?$LessonModel->classManage->class_id:0;
           $OrderItemModel = OrdersItems::findOne($item->order_sales_id);
           $ItemrelationModel = OrdersItemsRelation::find()->where(['orders_items_id'=>$item->order_sales_id])->one();
           $subCheckModel = SubstituteCheck::find()->where(['student_check_id'=>$item->id])->one();
           $ClassTeacherModel = ClassManageTeacher::find()->where(['class_id'=>$class_id])->one();
           $StudentModel = Student::findOne($item->student_id);
            $check_type = 0;
            $check_user = $item->student_id;
           if($subCheckModel != null){
               $check_type = 1;
               $check_user = $subCheckModel->userid;
           }
            $class_type = 'appointment';
           $is_scholarship = isset($ItemrelationModel->is_scholarship)?$ItemrelationModel->is_scholarship:1;
           if($is_scholarship == 2 ){
               $class_type = 'consume';
           }
            $is_frequency = isset($classstudent->is_frequency)?$classstudent->is_frequency:0;
           if($OrderItemModel->amount > 0  && $classstudent != null) {
               if ($is_frequency == 1) {
                   $price = round($ItemrelationModel->lesson_price / $ItemrelationModel->lesson, 2);
                   $settlement_price = 0;
                   if ($class_type == 'consume') {
                       if($ItemrelationModel->distribution_way > 0)
                       $settlement_price = round($price - ($price * $ItemrelationModel->distribution_proportion / 100), 2);
                   } else {
                       if($ItemrelationModel->subsidy_money > 0)
                       $settlement_price = round($ItemrelationModel->subsidy_money / $ItemrelationModel->lesson, 2);
                   }
                   $datas[] = [
                       'mechanic_id' => isset($OrderItemModel->mechanic_id) ? $OrderItemModel->mechanic_id : 0,
                       'goods_id' => isset($OrderItemModel->goods_id) ? $OrderItemModel->goods_id : 0,
                       'orders_item_id' => isset($OrderItemModel->id) ? $OrderItemModel->id : 0,
                       'orders_items_relation_id' => isset($ItemrelationModel->id) ? $ItemrelationModel->id : 0,
                       'teacher_id' => isset($ClassTeacherModel->teacher_id) ? $ClassTeacherModel->teacher_id : 0,
                       'customer_id' => isset($StudentModel->customer_id) ? $StudentModel->customer_id : 0,
                       'student_id' => $item->student_id,
                       'class_id' => $class_id,
                       'class_lesson_id' => $item->class_lesson_id,
                       'check_id' => $item->id,
                       'lesson' => $LessonModel->lesson,
                       'class_time' => $LessonModel->class_date,
                       'price' => $price,
                       'settlement_price' => $settlement_price,
                       'status' => 0,
                       'check_type' => $check_type,
                       'check_user' => $check_user,
                       'class_type' => $class_type,
                       'created_at' => time(),
                       'updated_at' => 0,
                   ];
               } else {
                   $date = date('Y-m-01', $LessonModel->class_date);
                   $startDay = strtotime(date('Y-m-01', $LessonModel->class_date));
                   $jiesuanStartDay = strtotime(date('Y-m-21', $LessonModel->class_date));
                   $jiesuanEndDay = strtotime(date('Y-m-22', $LessonModel->class_date));
                   $lastday = date('Y-m-d', strtotime("$date +1 month"));
                   if($LessonModel->class_date >= $jiesuanStartDay && $LessonModel->class_date < $lastday){ //21-月底时间
                       $newjiesuanStartDay = strtotime(date('Y-m-21', $LessonModel->class_date));
                       $newjiesuanEndDay = date('Y-m-22', strtotime("$date +1 month"));
                   }
                   if($LessonModel->class_date >= $startDay && $LessonModel->class_date < $jiesuanEndDay){  //1-21号上课
                       $newjiesuanStartDay = strtotime(date('Y-m-21', strtotime("$date -1 month")));
                       $newjiesuanEndDay = strtotime(date('Y-m-22', $LessonModel->class_date));
                   }
                   $moneymonths = 0;
                   if ($ItemrelationModel->deadline_type == 'month') {
                       if($ItemrelationModel->deadline> 0 ) {
                           $moneymonth = ($ItemrelationModel->lesson_price / $ItemrelationModel->deadline) * ($ItemrelationModel->distribution_proportion / 100);
                           $moneymonths = round(($ItemrelationModel->lesson_price / $ItemrelationModel->deadline) - $moneymonth, 2);
                       }
                   } else {
                       if($ItemrelationModel->deadline> 0) {
                           $moneymonth = ($ItemrelationModel->lesson_price / ($ItemrelationModel->deadline * 12)) * ($ItemrelationModel->distribution_proportion / 100);
                           $moneymonths = round(($ItemrelationModel->lesson_price / ($ItemrelationModel->deadline * 12)) - $moneymonth, 2);
                       }
                   }
                   $frequencyModel = CheckCount::find()->where(['student_id' => $item->student_id, 'is_frequency' => 0])->andWhere(['between', 'class_time', $newjiesuanStartDay, $newjiesuanEndDay])->one();
                   $settlement_price = 0;
                   if ($frequencyModel == null) {
                       $settlement_price = $moneymonths;
                   }
                   $newModel = new CheckCount();
                   $newModel->mechanic_id = isset($OrderItemModel->mechanic_id) ? $OrderItemModel->mechanic_id : 0;
                   $newModel->goods_id = isset($OrderItemModel->goods_id) ? $OrderItemModel->goods_id : 0;
                   $newModel->orders_item_id = isset($OrderItemModel->id) ? $OrderItemModel->id : 0;
                   $newModel->orders_items_relation_id = isset($ItemrelationModel->id) ? $ItemrelationModel->id : 0;
                   $newModel->teacher_id = isset($ClassTeacherModel->teacher_id) ? $ClassTeacherModel->teacher_id : 0;
                   $newModel->customer_id = isset($StudentModel->customer_id) ? $StudentModel->customer_id : 0;
                   $newModel->student_id = $item->student_id;
                   $newModel->class_id = $class_id;
                   $newModel->class_lesson_id = $item->class_lesson_id;
                   $newModel->check_id = $item->id;
                   $newModel->lesson = $LessonModel->lesson;
                   $newModel->class_time = $LessonModel->class_date;
                   $newModel->price = 0;
                   $newModel->settlement_price = $settlement_price;
                   $newModel->status = 0;
                   $newModel->check_type = $check_type;
                   $newModel->check_user = $check_user;
                   $newModel->class_type = $class_type;
                   $newModel->is_frequency = 1;
                   $newModel->save(false);
               }
           }
        }
//        print_r($datas);die;
        Fun::getSiteDb()->createCommand()->batchInsert('{{%check_count}}', ['mechanic_id', 'goods_id', 'orders_item_id', 'orders_items_relation_id', 'teacher_id', 'customer_id', 'student_id', 'class_id','class_lesson_id','check_id','lesson','class_time','price','settlement_price','status','check_type','check_user','class_type','created_at','updated_at'], $datas)->execute();
    }
}
